package com.chcit.mobile.mvp.packmanager.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.custom.view.util.DialogUtil;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.di.component.DaggerPackageManagerComponent;
import com.chcit.mobile.di.module.PackageManagerModule;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.entity.PackageUintBean;
import com.chcit.mobile.mvp.packmanager.adapter.PackageMergeAdapter;
import com.chcit.mobile.mvp.packmanager.adapter.PackageSubAdapter;
import com.chcit.mobile.mvp.packmanager.contract.PackageManagerContract;
import com.chcit.mobile.mvp.packmanager.presenter.PackageManagerPresenter;
import com.chcit.mobile.mvp.entity.PackageBean;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.toast.XToast;

import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class PackageManagerFragment extends ScanFragment<PackageManagerPresenter> implements PackageManagerContract.View {

    protected MenuTypeEnum type;
    @BindView(R.id.et_package_manager_packageNo)
    SuperInputEditText etPackageNo;
    @BindView(R.id.bt_package_manager_query)
    Button btQuery;
    @BindView(R.id.tv_package_manager_productName)
    TextView tvProductName;
    @BindView(R.id.tv_package_manager_productCode)
    TextView tvProductCode;
    @BindView(R.id.tv_package_manager_productSpec)
    TextView tvProductSpec;
    @BindView(R.id.tv_package_manager_lot)
    TextView tvLot;
    @BindView(R.id.tv_package_manager_guaranteeDate)
    TextView tvGuaranteeDate;
    @BindView(R.id.tv_package_manager_manufacturer)
    TextView tvManufacturer;
    @BindView(R.id.tv_package_manager_vendor)
    TextView tvVendor;

    @BindView(R.id.ll_package_manager_six)
    LinearLayout llSix;
    @BindView(R.id.tv_showSY)
    LinearLayout showSY;
    @BindView(R.id.tv_showZSL)
    LinearLayout showZSL;
    @BindView(R.id.fenbao_titel)
    LinearLayoutCompat fenbaoTitel;
    @BindView(R.id.bingbao_titel)
    LinearLayoutCompat bingbaoTitel;
    @BindView(R.id.tv_movement_qty)
    TextView tvQty;
    @BindView(R.id.tv_package_manager_qtyTotal)
    TextView tvQtyTotal;
    @BindView(R.id.tv_package_manager_uom)
    TextView tvUom;
    @BindView(R.id.tv_package_manager_remainingQty)
    TextView tvRemainingQty;
    @BindView(R.id.et_split_Qty)
    AppCompatEditText etSplitQty;
    @BindView(R.id.include_package_split)
    LinearLayout includePackageSplit;
    @BindView(R.id.bt_package_manager_ok)
    Button btOk;
    @BindView(R.id.lv_iteam_list)
    RecyclerView mRecyclerView;
    private PackageBean packageBean;
    private PackageMergeAdapter mAdapterM;
    private PackageSubAdapter mAdapterS;
    private List<PackageBean> packageBeanList = new ArrayList<>();
    private List<PackageUintBean> PackageUintBeanList = new ArrayList<>();
    private PackageUintBean PackageUintBean;


    public static PackageManagerFragment newInstance() {
        PackageManagerFragment fragment = new PackageManagerFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerPackageManagerComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .packageManagerModule(new PackageManagerModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_package_manager, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        switch (type) {
            case PACKAGE_SPLIT:
                mCommonToolbar.setTitleText("拆零加工");
                btOk.setText("拆零确认");
                includePackageSplit.setVisibility(View.VISIBLE);//设置控件可见
                showSY.setVisibility(View.VISIBLE);//剩余数量
                break;
            case PACKAGE_SUB:
                mCommonToolbar.setTitleText("定数分包");
                showSY.setVisibility(View.VISIBLE);//剩余数量
                btOk.setText("分包确认");
                fenbaoTitel.setVisibility(View.VISIBLE);//标题
                break;
            case PACKAGE_MERGE:
                mCommonToolbar.setTitleText("并包加工");
                bingbaoTitel.setVisibility(View.VISIBLE);//并包标题
                showZSL.setVisibility(View.VISIBLE);//可见
                btOk.setText("并包确认");
                break;
        }
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        etPackageNo.setText(barcodeData);
        getData();
    }

    private void showData() {
        if (packageBean != null) {
            tvGuaranteeDate.setText(packageBean.getGuaranteeDate());
            tvProductCode.setText(packageBean.getProductCode());
            tvLot.setText(packageBean.getLot());
            tvManufacturer.setText(packageBean.getManufacturer());
            tvProductName.setText(packageBean.getProductName());
            tvProductSpec.setText(packageBean.getProductSpec());
            tvQty.setText(packageBean.getQty().toString());
            tvVendor.setText(packageBean.getVendorName());
            tvUom.setText(packageBean.getUomName());
            switch (type) {
                case PACKAGE_MERGE://并包
                    int position = packageBeanList.indexOf(packageBean);
                    if (position >= 0) {
                        new MaterialDialog.Builder(getContext())
                                .title("提示")
                                .content("该条码已被扫过，是否删除？")
                                .negativeText("删除")
                                .positiveText("取消")
                                .onNegative((dialog, which) -> {
                                    clearAllData();
                                    mAdapterM.remove(position);
                                })
                                .build()
                                .show();
                        return;
                    }
                    mAdapterM.addData(packageBean);

                    break;
                case PACKAGE_SUB://分包
                    tvRemainingQty.setText(packageBean.getQty().toString());//剩余数量

                    JSONObject params = new JSONObject();
                    params.put("productId", packageBean.getProductId());
                    params.put("warehouseId", HttpClientHelper.getSelectWareHouse().getId());
                    assert mPresenter != null;
                    mPresenter.getPackageUnit(params, packageUnits -> {
                        mAdapterS.addData(packageUnits);

                    });
                    break;

                case PACKAGE_SPLIT://拆零
                    tvRemainingQty.setText(packageBean.getQty().toString());//剩余数量
                    break;

            }
        }

    }


    @OnClick({R.id.bt_package_manager_query, R.id.bt_package_manager_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_package_manager_query:
                getData();
                break;
            case R.id.bt_package_manager_ok:
                confirm();
                break;
        }
    }

    private void getData() {
        if (etPackageNo.getText().toString().isEmpty()) {
            return;
        }
        JSONObject params = new JSONObject();
        params.put("packageNo", etPackageNo.getText().toString());
        params.put("packageStatus", "S");//在库
        params.put("warehouseId", HttpClientHelper.getSelectWareHouse().getId());
        assert mPresenter != null;
        mPresenter.getPakcageInfo(params, list -> {
            packageBean = list.get(0);
            showData();
        });
    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initEvent();
        initRecyclerView();
    }

    private void initEvent() {

        switch (type) {

            case PACKAGE_MERGE:  //并包

                tvQty.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void afterTextChanged(Editable s) {
                        String text = s.toString();
                        String qtytotal = tvQtyTotal.getText().toString();
                        if (!text.isEmpty()) {
                            if (!qtytotal.isEmpty()) {
                                tvQtyTotal.setText((new BigDecimal(qtytotal)).add(new BigDecimal(text)).toString());
                            } else {
                                tvQtyTotal.setText((new BigDecimal(text)).add(new BigDecimal(0)).toString());
                            }
                        }
                    }
                });
                break;


            case PACKAGE_SUB://分包

                tvQtyTotal.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void afterTextChanged(Editable s) {
                        String text = s.toString();
//                if(!text.isEmpty()){
//
//                    tvQtyTotal.setText(packageBean.getQty().add(new BigDecimal(text)).toString());
//                }else{
//                    tvQtyTotal.setText(packageBean.getQty().add(new BigDecimal(0)).toString());
//                }

                    }
                });
                break;


            case PACKAGE_SPLIT://拆零

                etSplitQty.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void afterTextChanged(Editable s) {
                        String text = s.toString();
                        String qty = tvQty.getText().toString();
                        if(StringUtils.isNotBlank(qty)){
                            if (!text.isEmpty()) {
                                tvRemainingQty.setText((new BigDecimal(qty)).subtract(new BigDecimal(text)).toString());
                            } else {
                                tvRemainingQty.setText((new BigDecimal(qty)).subtract(BigDecimal.ZERO).toString());
                            }
                        }

                    }
                });
                break;


        }


    }

    public void initRecyclerView() {

        switch (type) {
            case PACKAGE_MERGE://并包

                mAdapterM = new PackageMergeAdapter(packageBeanList);
                mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                mAdapterM.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
                    // int itemClickPosition = -1;
                    @Override
                    public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                        if (position >= 0) {
                            new MaterialDialog.Builder(getContext())
                                    .title("提示")
                                    .content("是否删除？")
                                    .negativeText("删除")
                                    .positiveText("取消")
                                    .onNegative((dialog, which) -> {
                                        tvQtyTotal.setText(new BigDecimal(tvQtyTotal.getText().toString()).subtract(mAdapterM.getData().get(position).getQty()).toString());
                                        ;
                                        mAdapterM.remove(position);
                                    })
                                    .build()
                                    .show();
                            return false;
                        }
                        return true;
                    }

                    ;

                });

                mRecyclerView.setAdapter(mAdapterM);


                break;
            case PACKAGE_SUB://分包

                mAdapterS = new PackageSubAdapter(PackageUintBeanList);
                mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                mAdapterS.setOnCountNumber((v) -> {
                    tvRemainingQty.setText(new BigDecimal(tvRemainingQty.getText().toString()).add(v).toString());
                });
                mRecyclerView.setAdapter(mAdapterS);

                break;
        }

    }

    private void confirm() {


        switch (type) {
            case PACKAGE_MERGE://并包

                JSONObject params = new JSONObject();
                List<PackageBean> pas = mAdapterM.getData();
                if (pas.size() == 0) {
                    DialogUtil.showErrorDialog(getContext(), "没有数据！");
                    return;
                }
                params.put("line", pas);
                JSONObject data = new JSONObject();
                data.put("data", params);
                assert mPresenter != null;
                mPresenter.packageMergeConfirm(data, () -> {
                    showMessage("并包成功!");
                    clearAllData();
                    mAdapterM.getData().clear();//清空
                    mAdapterM.notifyDataSetChanged();//刷新
                });

                break;
            case PACKAGE_SUB://分包
                JSONObject paramsFB = new JSONObject();
                List<PackageUintBean> pasFB = mAdapterS.getData();
                BigDecimal rq = new BigDecimal(tvRemainingQty.getText().toString());
                if (rq.compareTo(BigDecimal.ZERO) < 0) {
                    DialogUtil.showErrorDialog(getContext(), "数量不足！");
                    return;
                }
                JSONArray arr = new JSONArray();
                for (int i = 0; i < pasFB.size(); i++) {
                    JSONObject line = new JSONObject();
                    line.put("unitPackQty", pasFB.get(i).getUnitPackQty());
                    line.put("packageCount", pasFB.get(i).getPackageCount());
                    arr.add(line);
                }

                paramsFB.put("line", arr);
                paramsFB.put("packageId", packageBean.getPackageId());
                assert mPresenter != null;
                mPresenter.packageSubConfirm(paramsFB, () -> {
                    showMessage("分包成功!");
                    clearAllData();
                    mAdapterS.getData().clear();//清空
                    mAdapterS.notifyDataSetChanged();//刷新
                });


                break;

            case PACKAGE_SPLIT://拆零
                JSONObject params2 = new JSONObject();
                String packageId = packageBean.getPackageId();
                String qty = etSplitQty.getText().toString();//拆分数量
                params2.put("packageId", packageId);
                params2.put("qty", qty);
                mPresenter.packageSplitConfirm(params2, () -> {
                    showMessage("拆零成功!");
                    clearAllData();
                });
                break;
        }

    }

    private void clearAllData() {
        tvGuaranteeDate.setText("");
        tvProductCode.setText("");
        tvLot.setText("");
        tvManufacturer.setText("");
        tvProductName.setText("");
        tvProductSpec.setText("");
        tvQtyTotal.setText("");
        tvQty.setText("");
        tvRemainingQty.setText("");
        tvUom.setText("");
        tvVendor.setText("");
    }

}
